package com.zjuee.gateway;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 动态加载受保护的url
 *
 * @author wu liang
 * @since 2020/8/13 9:54
 */
@Component
public class DynamicLoadUrl {
    private static transient final Logger log = LoggerFactory.getLogger(DynamicLoadUrl.class);

    @Resource
    private ApplicationContext applicationContext;

//    @Resource
////    private MenuService menuService;

    public Map<String, String> loadFilterChainDefinitions() {

        // 定义url拦截规则mapping
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        // 先从实现ShiroAuthenUrl接口的类中获取拦截规则，并加入到shiro拦截器
        Map<String, ShiroAuthenUrl> map = applicationContext.getBeansOfType(ShiroAuthenUrl.class);
        if (map != null && !map.isEmpty()) {
            for (String beanName : map.keySet()) {
                ShiroAuthenUrl shiroAuthenUrl = map.get(beanName);
                if (shiroAuthenUrl != null) {
                    filterChainDefinitionMap.putAll(shiroAuthenUrl.authenUrl());
                }
            }
        }

        //从数据库获取所有受保护的url
//        List<Menu> menus = menuService.findAuthorities();
//        // 此处以资源的url为key 以url为value 设置权限
//        if (menus != null && !menus.isEmpty()) {
//            for (Menu menu : menus) {
//                filterChainDefinitionMap.put(menu.getMenuUrl(), "hasPerms[" + menu.getMenuUrl() + "]");
//            }
//        }

        return filterChainDefinitionMap;
    }
}
